package cn.easybuy.controller;

import cn.easybuy.pojo.*;
import cn.easybuy.service.news.NewsService;
import cn.easybuy.service.order.OrderService;
import cn.easybuy.service.orderdetail.OrderDetailService;
import cn.easybuy.service.product.ProductService;
import cn.easybuy.service.productcategory.ProCategoryService;
import cn.easybuy.service.useraddress.UserAddressService;
import cn.easybuy.util.Constants;
import cn.easybuy.vo.ShoppingCart;
import cn.easybuy.vo.ProductCategoryVo;
import cn.easybuy.vo.ShoppingCartItem;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class PreController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private ProCategoryService proCategoryService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 跳转首页面
     * @return
     */
    @RequestMapping("/index")
    public String Index(HttpServletRequest request) throws InterruptedException{
       /*//显示新闻资讯
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        ServletContext application = request.getServletContext();//获取ServletContext对象
        //新闻资讯更新问题，即使更新（曾、删、改），延迟更新（定时器）
        List<News> news = (List<News>) application.getAttribute("news"); //从application对象获取新闻资讯集合
        if (news == null) {
            synchronized (this) {
                news = (List<News>) application.getAttribute("news");
                //第一次获取肯定是空
                if (news == null) {
                    //多线程并发安全问题:锁
                    //Thread.sleep(2000);
                    queryWrapper.orderByDesc("createTime").last(" limit 5");
                    news = newsService.list(queryWrapper);
                    application.setAttribute("news", news);
                }
            }
        }*/

        //显示全部商品分类:递归优化
       /* List<ProductCategoryVo> productCategoryVoList =(List<ProductCategoryVo>) application.getAttribute("productCategoryVoList");
        if (productCategoryVoList == null){
            synchronized (this){
                productCategoryVoList = (List<ProductCategoryVo>) application.getAttribute("productCategoryVoList");
                //第一次获取肯定是空
                if (productCategoryVoList == null) {
                    productCategoryVoList = new ArrayList<>();//返回前端的集合
                    //一级分类
                    List<ProductCategory> productCategoryList1 = proCategoryService.list(new QueryWrapper<ProductCategory>().eq("parentId",0).eq("type",1));
                    for (ProductCategory productCategory1 : productCategoryList1){
                         ProductCategoryVo productCategoryVo1 = new ProductCategoryVo();
                         productCategoryVo1.setProductCategory(productCategory1);

                         //二级分类
                        List<ProductCategory> productCategoryList2 = proCategoryService.list(new QueryWrapper<ProductCategory>().eq("parentId",productCategory1.getId()).eq("type",2));
                         for (ProductCategory productCategory2 : productCategoryList2){
                             ProductCategoryVo productCategoryVo2 = new ProductCategoryVo();
                             productCategoryVo2.setProductCategory(productCategory2);

                             //三级分类
                             List<ProductCategory> productCategoryList3 = proCategoryService.list(new QueryWrapper<ProductCategory>().eq("parentId",productCategory2.getId()).eq("type",3));
                                for (ProductCategory productCategory3 :productCategoryList3){
                                    ProductCategoryVo productCategoryVo3 = new ProductCategoryVo();
                                    productCategoryVo3.setProductCategory(productCategory2);
                                    productCategoryVo2.getProductCategoryVoList().add(productCategoryVo3);
                                }
                             productCategoryVo1.getProductCategoryVoList().add(productCategoryVo2);
                         }
                        productCategoryVoList.add(productCategoryVo1);
                    }
                    pcv(0, 1, productCategoryVoList);
                    application.setAttribute("productCategoryVoList", productCategoryVoList);
                }
            }
        }*/
        return "pre/index";
    }

    /**
     * 递归商品分类
     * @param parentId
     * @param type
     * @param productCategoryVoList
     */
    public void pcv(Integer parentId,Integer type, List<ProductCategoryVo> productCategoryVoList){
        //结束递归的条件
        if(type==4){
            return;
        }
        //重复做的事情
        //1、商品分类
        List<ProductCategory> productCategoryList = proCategoryService.list(new QueryWrapper<ProductCategory>().eq("parentId",parentId).eq("type", type));
        //2、遍历商品分类
        for(ProductCategory productCategory : productCategoryList){
            ProductCategoryVo productCategoryVo = new ProductCategoryVo();
            productCategoryVo.setProductCategory(productCategory);
            //递归调用
            pcv(productCategory.getId(),
                    type+1,productCategoryVo.getProductCategoryVoList());
            productCategoryVoList.add(productCategoryVo);
        }
    }

   /*@Value("${dir.url}")
    private String url;*/
    /**
     * 跳转到新闻资讯更多页面
     */
    @RequestMapping("/admin/news/queryNewsList")
    public String News(@RequestParam(defaultValue = "1") Integer currentPage,
                       HttpServletRequest request){
        //分页
        PageHelper.startPage(currentPage, 8);
        //显示新闻列表
        List<News> newsList = newsService.list();
        request.setAttribute("newsList",newsList);
        //分页数据
        PageInfo<News> pageInfo = new PageInfo<>(newsList);
        Map<String,Object> pager = new HashMap<>();
        pager.put("currentPage",pageInfo.getPageNum());
        pager.put("pageCount",pageInfo.getPages());
        pager.put("url","admin/news/queryNewsList?");
        request.setAttribute("pager",pager);

        return "backend/news/newsList";
    }

    /**
     * 查询新闻详情
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/admin/news/newsDetail")
    public String newsDetail(Integer id,HttpServletRequest request){
        News news = newsService.getById(id);
        request.setAttribute("news",news);
        return "backend/news/newsDetail";
    }

    /**
     * 分类商品的详情
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/Product/queryProductDeatil")
    public String queryProductDeatil(Integer id ,HttpServletRequest request){
        Product product =productService.getById(id);
        request.setAttribute("product",product);
        return "pre/product/productDeatil";
    }

    /**
     * 跳转首页
     * @return
     */
    @RequestMapping("/Home/index")
    public String Home (){
        return "pre/index";
   }

    /**
     * 跳转商品分类二三级详情
     * @param currentPage 页码从几开始
     * @param level 分类级别
     * @param category id
     * @param keyWord 搜索
     * @param request
     * @return
     */
    @RequestMapping("/Product/queryProductList")
    public String queryProductList(@RequestParam(defaultValue = "1") Integer currentPage,
                                   Integer level,Integer category,String keyWord,
                                   HttpServletRequest request){
        PageHelper.startPage(currentPage, 8);
        //显示商品列表
       /* List<Product> productList = productService.list(new QueryWrapper<Product>()
                .eq(level != null && level == 1, "categoryLevel1Id", category)
                .eq(level != null && level == 2, "categoryLevel2Id", category)
                .eq(level != null && level == 3, "categoryLevel3Id", category));*/

        List<Product> productList = productService.list(new QueryWrapper<Product>()
                                    .eq(category!=null&&level!=null,"categoryLevel"+level+"Id",category)
                                    .like(keyWord!=null,"name",keyWord)
                                    .or().like(keyWord!=null,"description",keyWord));
        request.setAttribute("productList",productList);

        //分页数据
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        Map<String,Object> pager = new HashMap<>();
        StringBuffer url = new StringBuffer("/Product/queryProductList?");
        if (category!=null && level!=null){
           url.append("&level=" + level + "&category=" + category);
        }
        if (keyWord!=null){
            url.append("&keyWord=" + keyWord );
        }
        pager.put("url",url);
        pager.put("currentPage",pageInfo.getPageNum());
        pager.put("pageCount",pageInfo.getPages());
        request.setAttribute("pager",pager);
        request.setAttribute("total",pageInfo.getTotal());
        request.setAttribute("keyWord",keyWord);

        return "pre/product/queryProductList";
    }

    /**
     * 添加收藏
     * @param id
     * @param session
     * @return
     */
    @RequestMapping("/Favorite/addFavorite")
    @ResponseBody
    public Object addFavorite(Integer id , HttpSession session) {
        List<Product> recentProducts = (List<Product>) session.getAttribute("recentProducts");
        if (recentProducts == null) {
            recentProducts = new ArrayList<>();
            session.setAttribute("recentProducts", recentProducts);
        }
        if (recentProducts.size() > 0) {
            for (Product product : recentProducts) {
                if (product.getId().equals(id)) {
                    recentProducts.remove(product);
                    return null;
                }
            }
        }
        recentProducts.add(productService.getById(id));
        return null;
    }

    /**
     * 收藏列表
     * @return
     */
    @RequestMapping("/Favorite/toFavoriteList")
    public String toFavoriteList(){
        return "pre/product/favoriteList";
    }

    /**
     *
     * 加入购物车
     * @param session
     * @param entityId
     * @param quantity
     * @return
     */
    @RequestMapping("/cart/add")
    @ResponseBody
    public Object add(HttpSession session,Integer entityId,Integer quantity){
        /*//判断是否登录
        Map<String,Object> map = new HashMap<>();
        if (session.getAttribute(Constants.LOGIN_USER) == null){
            map.put("status",0);
            map.put("message","请先登录!");
            return map;
        }else{
            Cart cart = (Cart)session.getAttribute("cart");
            if (cart == null){
                cart = new Cart();
                session.setAttribute("cart",cart);
            }
            map.put("status",1);
            for (ProductVo productVo :cart.getItems()){
                if (productVo.getProduct().getId().equals(entityId)){
                    productVo.setQuantity(productVo.getQuantity()+quantity);
                    return map;
                }
            }
            Product product = productService.getById(entityId);
            ProductVo productVo = new ProductVo();
            productVo.setProduct(product);
            productVo.setQuantity(quantity);
            cart.getItems().add(productVo);
            return map;
        }*/
        //判断是否登录
        Map<String,Object> map = new HashMap<>();
        if (session.getAttribute(Constants.LOGIN_USER) == null){
            map.put("message","请先登录!");
            return map;
        }
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("cart");
        if (shoppingCart == null){
            shoppingCart = new ShoppingCart();
            session.setAttribute("cart",shoppingCart);
        }
        map.put("status",1);
        shoppingCart.addItem(productService.getById(entityId),quantity);
        shoppingCart.setSum(shoppingCart.getTotalCost());
        return map;
    }

    /**
     * 刷新购物车
     * @return
     */
    @RequestMapping("/cart/refreshCart")
    public String refreshCart(){
        return "common/pre/searchBar";
    }

    /**
     * 跳转结算页面
     * @return
     */
    @RequestMapping("/cart/toSettlement")
    public String toSettlement(){
        return "pre/settlement/toSettlement";
    }

    /**
     * 结算 加载购物车列表
     * @return
     */
    @RequestMapping("/cart/settlement1")
    public String settlement1(){
        return "pre/settlement/settlement1";
    }

    /**
     * 修改/删除购物车列表
     * @param session
     * @param entityId
     * @param quantity
     * @return
     */
    @RequestMapping("/cart/modCart")
    @ResponseBody
    public Object modCart(HttpSession session,Integer entityId,Integer quantity){
        Map<String ,Object> map = new HashMap<>();
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        for (ShoppingCartItem item : cart.getItems()){
            if (item.getProduct().getId().equals(entityId)){
                map.put("status",1);
                if (quantity == 0){
                    cart.getItems().remove(item);
                    cart.setSum(cart.getTotalCost());
                    return map;
                }
                item.setQuantity(quantity);
                cart.setSum(cart.getTotalCost());
                return map;
            }
        }
        map.put("status",0);
        map.put("message","服务器异常");
        return map;
    }

    /**
     * 结算 形成预备订单(地址)
     * @param request
     * @return
     */
    @RequestMapping("/cart/settlement2")
    public String settlement2(HttpServletRequest request){
        User loginUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);//获取登录人
        List<UserAddress> userAddressList = userAddressService.list(new QueryWrapper<UserAddress>().eq("userId",loginUser.getId()));
        request.setAttribute("userAddressList",userAddressList);
        return "pre/settlement/settlement2";
    }

    /**
     * 结算 提交订单
     * @param addressId
     * @param newAddress
     * @param newRemark
     * @param session
     * @param request
     * @return
     */
    @RequestMapping("/cart/settlement3")
    public String settlement3(Integer addressId,String newAddress,
                              String newRemark,HttpSession session,
                              HttpServletRequest request){

        User loginUser = (User) session.getAttribute(Constants.LOGIN_USER);
        //新地址
        if (addressId == -1){
            UserAddress userAddress = new UserAddress();
            userAddress.setAddress(newAddress);
            userAddress.setCreateTime(new Date());
            userAddress.setRemark(newRemark);
            userAddress.setUserId(loginUser.getId());
            userAddressService.save(userAddress);
        }else{
            //老地址
            newAddress = userAddressService.getById(addressId).getAddress();
        }
        //下单
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        Order order = new Order();
        order.setCost(cart.getSum());
        order.setCreateTime(new Date());
        order.setUserId(loginUser.getId());
        order.setLoginName(loginUser.getLoginName());
        order.setUserAddress(newAddress);
        order.setSerialNumber("D"+System.currentTimeMillis()+"U" + loginUser.getId());
        order.setOrderDetailList(new ArrayList<>());

        //订单详情
        for (ShoppingCartItem item:cart.getItems()){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setCost(item.getCost());
            orderDetail.setProductId(item.getProduct().getId());
            orderDetail.setQuantity(item.getQuantity());
            order.getOrderDetailList().add(orderDetail);
        }
        if (orderService.saveOrder(order)){
            request.setAttribute("currentOrder",order);
            session.removeAttribute("cart");//清空购物车
            return "pre/settlement/settlement3";
        }
        return "{\"message\":\"下单失败\"}";
    }


}
